using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using Schemata.Core;

namespace Awaken.CodeGen.Controls
{
    public class TableBasedControl : System.Web.UI.UserControl
    {
        public string Namespace
        {
            get { return Request.Params["Namespace"].Trim(); }
        }

        public string Assembly
        {
            get { return Request.Params["Assembly"].Trim(); }
        }

        public string ConnectionString
        {
            get { return Request.Params["ConnectionString"].Trim(); }
        }

        public string TableName
        {
            get { return Request.Params["TableName"].Trim(); }
        }

        public string DatabaseName
        {
            get { return Request.Params["DatabaseName"].Trim(); }
        }

        protected Database database;
        public Database Database
        {
            get 
            {
                if (database == null)
                {
                    SqlServerSchemaProvider sqlProvider = new SqlServerSchemaProvider();
                    DatabaseSchema databaseSchema = new DatabaseSchema(DatabaseName,sqlProvider, ConnectionString);

                    database = new Database(databaseSchema);
                }
                return database;
            }
        }
        
        protected Table table;
        public Table Table
        {
            get
            {
                if (table == null)
                {
                    foreach (Table obj in Database.Tables)
                    {
                        if (obj.TableName == TableName)
                        {
                            table = obj;
                            break;
                        }
                    }

                    if (table == null)
                        throw new NullReferenceException("Unable to find " + TableName);
                }
                return table;
            }
        }

        public string ClassName
        {
            get { return Table.ClassName; }
        }
    }
}
